<template>
  <div id="app">
    <div id="map"></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import Map from "ol/Map";
import View from "ol/View";
import ImageLayer from "ol/layer/Image";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import ImageCanvasSource from "ol/source/ImageCanvas";
import Static from "ol/source/ImageStatic";
import WKT from "ol/format/WKT";
import GeoJSON from "ol/format/GeoJSON";

import { Fill, Stroke, Circle, Style } from "ol/style";
import axios from "axios";

import * as turf from "@turf/turf";
import { operation } from "@/operation";
import Geolocation from "ol/Geolocation";

@Component({})
export default class App extends Vue {
  mounted() {
    this.initMap();
  }
  initMap() {
    function correct(coordinates: any) {
      const [[p1, p2, p3, p4]] = coordinates;
      let x = p4[0] - (p1[0] - p2[0]);
      let y = p4[1] - (p1[1] - p2[1]);
      return [[p1, p2, [x, y], p4, p1]];
    }
    var vLayer = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
    });

    operation.map = new Map({
      target: "map",
      view: new View({
        center: fromLonLat([84.925, 43.56], "EPSG:3857"),
        zoom: 6,
      }),
      layers: [
        new TileLayer({
          source: new XYZ({
            attributions:
              "© <a href='http://www.chinatoprs.com/' target='_blank'> 中测新图(北京)遥感技术有限责任公司 </a>",
            attributionsCollapsible: false,
            url:
              "http://t{0-7}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=ab1846502fcc2340e75c1d9ceb67c58b",
          }),
        }),
        new TileLayer({
          source: new XYZ({
            url:
              "http://t{0-7}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=ab1846502fcc2340e75c1d9ceb67c58b",
          }),
        }),
        new TileLayer({
          source: new XYZ({
            url:
              "http://t{0-7}.tianditu.gov.cn/ibo_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ibo&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=ab1846502fcc2340e75c1d9ceb67c58b",
          }),
        }),
        // vLayer,
      ],
    });
    var geolocation = new Geolocation({
      tracking: true,
      // take the projection to use from the map's view
      projection: operation.map.getView().getProjection(),
    });
    // console.log(geolocation.getAccuracy());
    // listen to changes in position
    geolocation.on("change", function (evt: any) {
      console.log(evt);
      console.log(geolocation.getPosition());
    });
    // axios.get("/data.json").then(async ({ data }: any) => {
    //   let { list } = data.data;
    //   list = list.filter((i: any) => i.flag);
    //   console.log(list.length);
    //   // list = list.slice(0, 500);
    //   this.WktFormate(vLayer, map, list);
    // });
  }

  addImageLayers(list: any, map: any) {
    var imgLayer = new ImageLayer({ id: "layerIddada" });
    var imgSource = new ImageCanvasSource({
      ratio: 1,
      canvasFunction: function (
        extent: any,
        resolution: any,
        ratio: any,
        size: any,
        Projection: any
      ) {
        var canvas = document.createElement("canvas");
        canvas.setAttribute("width", size[0]);
        canvas.setAttribute("height", size[1]);
        var context: any = canvas.getContext("2d");

        for (let item of list) {
          const exentTopLeft = [extent[0], extent[3]];
          const [[p1, p2, p3, p4]] = item.boundary.getCoordinates();
          const [pxp1, pxp2, pxp3, pxp4] = [
            map.getPixelFromCoordinate(p1),
            map.getPixelFromCoordinate(p2),
            map.getPixelFromCoordinate(p3),
            map.getPixelFromCoordinate(p4),
          ];
          const pxExent = map.getPixelFromCoordinate(exentTopLeft);
          const tan1 = (p2[1] - p1[1]) / (p2[0] - p1[0]);
          const tan2 = (p4[0] - p1[0]) / (p4[1] - p1[1]);
          const p1Top2 = pxp2[0] - pxp1[0];
          const p1Top4 = pxp4[1] - pxp1[1];
          context?.setTransform(
            1,
            -tan1,
            -tan2,
            1,
            pxp1[0] - pxExent[0],
            pxp1[1] - pxExent[1]
          );
          context?.drawImage(item.img, 0, 0, p1Top2, p1Top4);
        }
        return canvas;
      },
    });
    imgLayer.setSource(imgSource);
    map.addLayer(imgLayer);
  }

  async WktFormate(vLayer: any, map: any, list: any) {
    for (let obj of list) {
      obj["boundary"] = new WKT().readGeometry(obj.boundary, {
        dataProjection: "EPSG:4326",
        featureProjection: "EPSG:3857",
      });

      const newFe = new Feature({
        ...obj,
      });

      //
      obj.url = "http://192.168.0.202:8081/quickView/" + obj.quickViewUrl;
      newFe.setGeometryName("boundary");
      const img = new Image();
      img.src = obj.url;
      await new Promise((resolve) => {
        img.onload = function () {
          resolve(true);
        };
      });

      obj.img = img;
      vLayer.getSource().addFeature(newFe);
    }
    this.addImageLayers(list, map);

    //  this.addImageLayer(obj.boundary, url, obj.entityId + "", map);
  }
}
</script>

<style lang="less">
#map {
  height: calc(100vh - 70px);
  width: calc(100% - 400px);
  float: left;
}
</style>
